package com.njbdqn.mydemo.controllers;

import java.io.File;	
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.njbdqn.mydemo.services.StudentService;
import com.njbdqn.mydemo.vo.Students;

@Controller
@Scope("prototype")
public class UploadController {
	@Autowired
	private StudentService studentService;
	
	@InitBinder
	public void bind(WebDataBinder wdb){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		sdf.setLenient(true);
		wdb.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
	}
	
	@RequestMapping("/upload.do")
	public String up(@RequestParam("file")MultipartFile file,Students stu,HttpSession session) throws Exception{
		//�ϴ�
		String path = session.getServletContext().getRealPath("/upload");
		File fpath = new File(path);
		if(!fpath.exists()){
			fpath.mkdirs();
		}
		String newName = studentService.getNewName(file.getOriginalFilename());
		
		File saveFile = new File(path,newName);
		file.transferTo(saveFile);
		
		stu.setPhoto(newName);
		studentService.saveStu(stu);
		
		return "index.jsp";
	}
}
